/*
	   _           _      _           _     _ 
	  (_)         | |    | |         (_)   | |
	   _ _   _ ___| |_ __| |_ __ ___  _  __| |
	  | | | | / __| __/ _` | '__/ _ \| |/ _` |
	  | | |_| \__ \ || (_| | | | (_) | | (_| |
	  | |\__,_|___/\__\__,_|_|  \___/|_|\__,_|
	 _/ |                                     
	|__/ 
	
	Copyright 2013 Caspar Isemer and and Eva Krueger, http://justdroid.org
	
	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at
	
		http://www.apache.org/licenses/LICENSE-2.0
	
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License. 
*/

package org.justdroid.justdroid;

import java.util.ArrayList;

import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Data;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class SaveContact extends JustDroidActivity {

	/** Declare variables and UI elements **/
	private EditText editName, editNumber, editEmail;
	private TextView txtType;
	private Button btnSave;
	private TextWatcher textWatcher;
	private Spinner spinnerType;
	private SpinnerAdapter adapter;
	private String number;
	private int typeIndex;
	private boolean editFlag ;
	
	void attachKeyListener(final Button button) {
		button.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
				if(keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
					switch(keyCode) {
					case KeyEvent.KEYCODE_DPAD_CENTER:
					case KeyEvent.KEYCODE_ENTER:
						saveAndGiveFeedback();
						break;
					}
				}
				return false;
			}
		});
	}
	
	/** Function to attach onTouchListener and onFocusListener to the EditTexts **/
	void attachOnTouchAndFocusListener(final EditText editText) {
		final String text = editText.getText().toString().trim();
		/*editText.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				//vibrate
				Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			    vibrator.vibrate(500);
				if(text.equals("")) {
					//empty EditText
					TTS.speak(editText.getContentDescription().toString());
				}
				else {
					TTS.speak(editText.getText().toString());
				}
				return false;
			}
		});*/
		
		editText.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View view, boolean hasFocus) {
				if(hasFocus) {
					if(text.equals("")) {
						//empty EditText
						TTS.speak(editText.getContentDescription().toString());
					}
					else {
						TTS.speak(editText.getText().toString());
					}
				}
			}
		});
	}
	
	/** Function to save the new contact **/
	boolean saveContact() {
		
		ArrayList<ContentProviderOperation> op_list = new ArrayList<ContentProviderOperation>(); 
	    op_list.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI) 
	            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null) 
	            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null) 
	            //.withValue(RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE_DEFAULT) 
	            .build()); 

	    // first and last names 
	    op_list.add(ContentProviderOperation.newInsert(Data.CONTENT_URI) 
	            .withValueBackReference(Data.RAW_CONTACT_ID, 0) 
	            .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE) 
	            .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, this.editName.getText().toString())
	            .build()); 

	    op_list.add(ContentProviderOperation.newInsert(Data.CONTENT_URI) 
	            .withValueBackReference(Data.RAW_CONTACT_ID, 0) 
	            .withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
	            .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, this.number)
	            .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, this.typeIndex)
	            .withValue(ContactsContract.CommonDataKinds.Phone.LABEL, this.spinnerType.getSelectedItem().toString())
	            .build());
	    op_list.add(ContentProviderOperation.newInsert(Data.CONTENT_URI) 
	            .withValueBackReference(Data.RAW_CONTACT_ID, 0)
	            .withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
	            .withValue(ContactsContract.CommonDataKinds.Email.DATA, editEmail.getText().toString())
	            .build());

	    try{ 
	        @SuppressWarnings("unused")
			ContentProviderResult[] results = getContentResolver().applyBatch(ContactsContract.AUTHORITY, op_list); 
	    }catch(Exception e){ 
	        e.printStackTrace();
	       return false;
	    } 
	    return true;
	}
	
	/** Function to edit a contact **/
	boolean editContact(String id) {
		ArrayList<ContentProviderOperation> op_list = new ArrayList<ContentProviderOperation>(); 
		
		ContentResolver cr = getContentResolver();
		 
        String where =  Data.RAW_CONTACT_ID +"=?";
        String[] params = new String[] {id};

		Cursor phoneCur = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, where, params, null);
        phoneCur.moveToFirst();
        
       
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
       
        // first and last names 
        ops.add(ContentProviderOperation.newUpdate(ContactsContract.RawContacts.CONTENT_URI) 
        		.withSelection(Data._ID + "=?", new String[]{id})
	            .withValue("display_name", this.editName.getText().toString())
	            .build()); 
      
	    op_list.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI) 
	    		.withSelection(Data._ID + "=?", new String[]{id})
	            .withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
	            .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, this.editNumber.getText().toString())
	            .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, this.typeIndex)
	            .withValue(ContactsContract.CommonDataKinds.Phone.LABEL, this.spinnerType.getSelectedItem().toString())
	            .build());
	    op_list.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI) 
	    		.withSelection(Data._ID + "=?", new String[]{id})
	            .withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
	            .withValue(ContactsContract.CommonDataKinds.Email.DATA, editEmail.getText().toString())
	            .build());

       
        phoneCur.close();
        
        try {
			ContentProviderResult[] result = cr.applyBatch(ContactsContract.AUTHORITY, ops);
			if(result[0] == null)
				return false;
			return true;
		} catch (RemoteException e) {
			e.printStackTrace();
			return false;
		} catch (OperationApplicationException e) {
			e.printStackTrace();
			return false;
		}   
	}
	
	void saveAndGiveFeedback() {
		if(editFlag == true) {
			//get Id of contact
			String id = new ContactManager(getApplicationContext()).getId(SaveContact.this.number);
			//edit contact
			if(editContact(id)) {
				Toast.makeText(getApplicationContext(), getResources().getString(R.string.contactupdated), Toast.LENGTH_SHORT).show();
				if(Utils.isAccessibilityEnabled(getApplicationContext()))
					TTS.speak(getResources().getString(R.string.contactupdated));
				finish();
			}
			else {
				Toast.makeText(getApplicationContext(), getResources().getString(R.string.contactnotupdated), Toast.LENGTH_SHORT).show();
				if(Utils.isAccessibilityEnabled(getApplicationContext()))
					TTS.speak(getResources().getString(R.string.contactnotupdated));
			}
		}
		else {
			if(saveContact()) {
				Toast.makeText(getApplicationContext(), getResources().getString(R.string.contactsaved), Toast.LENGTH_SHORT).show();
				if(Utils.isAccessibilityEnabled(getApplicationContext()))
					TTS.speak(getResources().getString(R.string.contactsaved));
				finish();
			}
			else {
				Toast.makeText(getApplicationContext(), getResources().getString(R.string.contactnotsaved), Toast.LENGTH_SHORT).show();
				if(Utils.isAccessibilityEnabled(getApplicationContext()))
					TTS.speak(getResources().getString(R.string.contactnotsaved));
			}
		}
	}
	
	/** Create the Contact Details menu activity **/
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.savecontact);
		super.onCreate(savedInstanceState);
		
		/** get UI elements **/
		editName = (EditText) findViewById(R.id.editName);
		editNumber = (EditText) findViewById(R.id.editNumber);
		editEmail = (EditText) findViewById(R.id.editEmail);
		txtType = (TextView) findViewById(R.id.txtType);
		btnSave = (Button) findViewById(R.id.btnSave);
		spinnerType = (Spinner) findViewById(R.id.spinnerType);
		adapter = new SpinnerAdapter(getApplicationContext(), Utils.numberType);
		spinnerType.setAdapter(adapter);
		
		if(getIntent().getExtras() != null) {
			this.number = getIntent().getExtras().getString("number");
			editNumber.setText(this.number);
			if(getIntent().getExtras().getString("name") != null) {
				editName.setText(getIntent().getExtras().getString("name"));
			}
			if(getIntent().getExtras().getString("email") != null) {
				editEmail.setText(getIntent().getExtras().getString("email"));
			}
			if(getIntent().hasExtra("edit")) {
				editFlag = getIntent().getExtras().getBoolean("edit");
			}
		}
		
		
		textWatcher = new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
				if(Utils.isAccessibilityEnabled(getApplicationContext()))
					TTS.speak(TTS.readNumber(cs.toString()));
			}
			
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {				
			}
			
			@Override
			public void afterTextChanged(Editable arg0) {				
			}
		};
		
		editName.addTextChangedListener(textWatcher);
		editEmail.addTextChangedListener(textWatcher);
		editNumber.addTextChangedListener(textWatcher);
		
		/*txtType.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View view, MotionEvent arg1) {
				giveFeedback(((TextView)view).getText().toString());
				return false;
			}
		});*/
		
		txtType.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View view, boolean hasFocus) {
				if(hasFocus) {
					giveFeedback(((TextView)view).getText().toString());
				}
			}
		});
		
		/*spinnerType.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				//vibrate
				Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			    vibrator.vibrate(500);
				return false;
			}
		});*/
		
		spinnerType.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				if(spinnerType.getSelectedItem().toString().equalsIgnoreCase("mobile")) {
					SaveContact.this.typeIndex = ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;
				}
				else if(spinnerType.getSelectedItem().toString().equalsIgnoreCase("home")) {
					SaveContact.this.typeIndex = ContactsContract.CommonDataKinds.Phone.TYPE_HOME;
				}
				else if(spinnerType.getSelectedItem().toString().equalsIgnoreCase("work")) {
					SaveContact.this.typeIndex = ContactsContract.CommonDataKinds.Phone.TYPE_WORK;
				}
				else if(spinnerType.getSelectedItem().toString().equalsIgnoreCase("workmobile")) {
					SaveContact.this.typeIndex = ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE;
				}
				else if(spinnerType.getSelectedItem().toString().equalsIgnoreCase("work")) {
					SaveContact.this.typeIndex = ContactsContract.CommonDataKinds.Phone.TYPE_WORK;
				}
				else if(spinnerType.getSelectedItem().toString().equalsIgnoreCase("pager")) {
					SaveContact.this.typeIndex = ContactsContract.CommonDataKinds.Phone.TYPE_PAGER;
				}
				else if(spinnerType.getSelectedItem().toString().equalsIgnoreCase("other")) {
					SaveContact.this.typeIndex = ContactsContract.CommonDataKinds.Phone.TYPE_OTHER;
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
		
		/*btnSave.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View view, MotionEvent arg1) {
				giveFeedback(((Button)view).getText().toString());
				return false;
			}
		});*/
		
		btnSave.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View view, boolean hasFocus) {
				if(hasFocus) {
					giveFeedback(((Button)view).getText().toString());
				}
			}
		});
		
		btnSave.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				saveAndGiveFeedback();
			}
		});
		
		attachKeyListener(btnSave);
		
		attachOnTouchAndFocusListener(editName);
		attachOnTouchAndFocusListener(editNumber);
		attachOnTouchAndFocusListener(editEmail);
		/** Put most everything before here **/
	}
	
	@Override
	public void onResume() {
		super.onResume();
		//TTS.speak(getResources().getString(R.string.savecontact));
		
		//get the root layout
		LinearLayout layout = (LinearLayout) findViewById(R.id.savecontact);
		Utils.applyFontColorChanges(getApplicationContext(), layout);  Utils.applyFontSizeChanges(getApplicationContext(), layout);  Utils.applyFontTypeChanges(getApplicationContext(), layout);
	}
}
